/**
 * time: 2025-09-16
 * author: XJ
 * description: 数字化改造情况
 */

import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Row,
  Select,
  Space,
  Steps,
  TreeSelect,
  Upload,
  UploadProps,
} from 'antd';
import { Col } from 'antd/lib';
import dayjs from 'dayjs';
import area from '@/components/staticFile/region_options.json';
import product from '@/components/staticFile/product_options.json';
import TextArea from 'antd/es/input/TextArea';
import chinaEconomy from '@/components/staticFile/industry_classification_options.json';
import { UploadOutlined } from '@ant-design/icons';
import { useLocation, useModel, useNavigate } from '@umijs/max';
import condition from '@/components/staticFile/treeSelect.json';
import { useEffect, useRef, useState } from 'react';
import { confirmDigital, situation, step2, uploadFile } from '@/services/apis/companyRegister';
import { page } from '@/services/apis/serviceProviderRegister';

// 统一样式常量
const COMMON_FIELD_STYLE = { width: '100%', height: 40, borderRadius: 4 };
const FORM_LAYOUT = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
  layout: 'horizontal' as const,
  
  size: 'middle' as const,
};

const StepThreePage: React.FC = (props) => {
  const onFinish = (values: any) => { };
  const onFinishFailed = (values: any) => { };
  const { stepProps, setStepProps } = useModel('DigitalizationManager.stepProps');
  const [senceList, setSenceList] = useState<any[]>([]);
  const { initialState, setInitialState } = useModel('@@initialState');
  const [productNameList, setProductNameList] = useState<any[]>([])
  const [connectServiceList, setConnectServiceList] = useState<any[]>([])
  const [xydmList, setXydmList] = useState<any[]>([])
  const [hetongList, setHetongList] = useState<{ [key: string]: [] }>({})
  const { dataGlobal, setDataGlobal } = useModel('DigitalizationManager.dataGlobal');
  const navigate = useNavigate();
  const loaction = useLocation()
  const [form] = Form.useForm();
  const connectService = useRef<any>({})
  const buildFullPathMap = (
    nodes: any[],
    parentPath: string[] = [],
    map: Record<string, string[]> = {},
  ) => {
    nodes.forEach((node) => {
      const currentPath = [...parentPath, node.title];
      map[node.value] = currentPath;
      if (node.children && node.children.length) {
        buildFullPathMap(node.children, currentPath, map);
      }
    });
    return map;
  };

  const fullPathMap = buildFullPathMap(condition);
  const convertNode = (node: any) => ({
    title: node.title,
    value: node.value,
    disabled: node.children && node.children.length > 0, // 非叶子节点禁用
    children: node.children?.map(convertNode),
  });

  useEffect(() => {
    page({
      current: "1", size: "10000",
      // status:"approved"
    }).then(res => {
      const { code, data } = res;
      if (code == "0") {
        const productNameList: any[] = [];
        const connectServiceList: any[] = [];
        const xydmList: any[] = [];
        data.records.forEach((item: any) => {
          const product = {
            value: item.productName,
            label: item.productName
          }
          productNameList.push(product)
          const service = {
            value: item.supplierName,
            label: item.supplierName
          }
          connectServiceList.push(service)
          const xydm = {
            value: item.xydm,
            label: item.xydm
          }
          xydmList.push(xydm)
          connectService.current[item.productName] = {supplierName:item.supplierName,xydm:item.xydm}
        })

        setProductNameList(productNameList);
        setConnectServiceList(connectServiceList)
        setXydmList(xydmList)
      }
    })
    form.setFieldsValue(dataGlobal.setpThree);
    setHetongList(dataGlobal.threeHetong)
  }, [dataGlobal.setpThree, dataGlobal.threeHetong])

  const submitFun = () => {
    form.validateFields().then(values => {
      // values.digitalContentList.forEach((item: { changeContract: string[]; }) => item.changeContract = ["xxx"])
      values.companyId = (initialState?.currentUser as any).data.id,
        step2(values).then(res => {
          const { code } = res
          if (code == "0") {
            navigate("/api_status_page", {
              state: {
                title: "企业项目备案",
                message: "企业项目备案暂存成功",
                callbackUrl: loaction.pathname
              }
            });
          } else {
            navigate("/api_status_page", {
              state: {
                title: "企业项目备案",
                message: "企业项目备案暂存失败",
                callbackUrl: loaction.pathname
              }
            });
          }
        })
    })
  }

  const confirmFun = () => {
    form.validateFields().then(values => {
      // values.digitalContentList.forEach((item: { changeContract: string[]; }) => item.changeContract = ["xxx"])
      values.companyId = (initialState?.currentUser as any).data.id,
        confirmDigital(values).then(res => {
          const { code } = res;
          if (code == "0") {
            navigate("/api_status_page", {
              state: {
                title: "企业项目备案",
                message: "企业项目备案提交成功",
                callbackUrl: loaction.pathname
              }
            });
            //message.success("提交成功")
          } else {
            navigate("/api_status_page", {
              state: {
                title: "企业项目备案",
                message: "企业项目备案提交失败",
                callbackUrl: loaction.pathname
              }
            });
          }
        })
    })

    // form.validateFields().then(values => {
    //   values.digitalContentList.forEach((item: { changeContract: string[]; }) => item.changeContract = ["xxx"])
    //   values.companyId = (initialState?.currentUser as any).data.id,
    //     step2(values).then(res => {
    //       const { code } = res
    //       if (code == "0") {
    //         //message.success("暂存成功")
    //       }
    //     })
    // })
  }

  const handleAutoUpload = async (file: any, formPath: any) => {

    try {
      const response = await uploadFile(file)
      if (response.code == "0") {
        setHetongList(prev => ({ ...prev, [formPath.join("_")]: [{ name: response.data.filename, uid: Math.random().toString() }] }))
        form.setFieldValue(formPath, [response.data])

      }
    } catch (error) {
    }
  };

  return (
    <div
      style={{
        padding: '20px',
        boxSizing: 'border-box',
        backgroundColor: '#f8f9fa',
        height: '100%',
        overflow: 'hidden',
      }}
    >
      <div
        style={{
          backgroundColor: '#fff',
          padding: '20px',
          borderRadius: 8,
          boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
          height: '100%',
          overflowY: 'auto',
        }}
      >
        <Form disabled={dataGlobal.stepThreeDisabled} {...FORM_LAYOUT} onFinish={onFinish} form={form} onFinishFailed={onFinishFailed}>
          {/* 基本信息组 */}
          <div style={{ marginBottom: 24 }}>
            <div
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              基本情况
            </div>

            {/* <Form.Item
              name="enterpriseName"
              label="企业名称"
              rules={[{ required: true, message: '请输入企业名称' }]}
              style={{ marginBottom: 20 }}
            >
              <Input style={COMMON_FIELD_STYLE} />
            </Form.Item> */}
            <Form.Item label="数字化水平等级(改造前)" style={{ marginBottom: 20 }}>

              <Space.Compact style={{ width: '100%' }}>
                <Form.Item
                  name="digitalLevel"
                  noStyle
                  rules={[{ required: true, message: '请选择数字化水平等级' }]}

                >
                  <Select
                    style={{ ...COMMON_FIELD_STYLE, flex: 1 }}
                    // 添加表单绑定属性
                    value={form.getFieldValue('digitalLevel')}
                    onChange={(value) => form.setFieldValue('digitalLevel', value)}
                  >
                    <Select.Option value="level1">一级</Select.Option>
                    <Select.Option value="level2">二级</Select.Option>
                    <Select.Option value="level3">三级</Select.Option>
                    <Select.Option value="level4">四级</Select.Option>
                  </Select>
                </Form.Item>

                <Button
                  style={{ ...COMMON_FIELD_STYLE, width: 'auto' }}
                  type="primary"
                  onClick={() =>
                    window.open(
                      'https://ucenter.miit.gov.cn/login.jsp?toUrl=http%3A%2F%2Fzjtx.miit.gov.cn%2Fqyxx%2Fgotoszhsp',
                    )
                  }
                >
                  去测试
                </Button>
              </Space.Compact>
            </Form.Item>
            <Form.Item
              name="transformationInvestment"
              label="改造总花费(万元)"
              rules={[{ required: true, message: '请输入改造总花费', pattern: /^\d+(\.\d+)?$/ }]}
              style={{ marginBottom: 20 }}
            >
              <Input style={COMMON_FIELD_STYLE} />
            </Form.Item>
          </div>

          <div style={{ marginBottom: 24 }}>
            <div style={{ borderBottom: '1px solid #e8e8e8', marginBottom: 20 }}></div>

            <div
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              新增/修改数字化改造内容
            </div>
            <Form.List name="digitalContentList">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <div
                      key={key}
                      style={{
                        marginBottom: 24,
                        borderBottom: '1px solid #e8e8e8',
                        paddingBottom: 16,
                      }}
                    >
                      <Row justify="space-between" align="middle">
                        <Col>
                          <div
                            style={{
                              fontSize: 16,
                              fontWeight: 500,
                              color: '#1f2937',
                              marginBottom: 12,
                              marginLeft: 12,
                            }}
                          >
                            内容 {name + 1}
                          </div>
                        </Col>
                        <Col>
                          <Popconfirm title="是否删除" onConfirm={() => remove(name)}>
                            <Button type="link" danger>
                              删除
                            </Button>
                          </Popconfirm>

                        </Col>
                      </Row>
                      <Form.Item
                        {...restField}
                        label="产品以及解决方案名称"
                        name={[name, 'productName']}
                        rules={[{ required: true, message: '请选择产品以及解决方案名称' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Select onChange={(value) => {
                          const supplierNames = value.map((item: string | number) => connectService.current[item].supplierName)
                          const xydms = value.map((item: string | number) => connectService.current[item].xydm)
                          form.setFieldValue(
                            ["digitalContentList", name, 'connectService'], 
                            [...supplierNames])
                          form.setFieldValue(
                            ["digitalContentList", name, 'craditCode'], 
                            [...xydms])
                        }} mode="tags" placeholder="请选择产品以及解决方案名称" options={productNameList} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="关联服务商"
                        name={[name, 'connectService']}
                        rules={[{ required: true, message: '请选择关联服务商' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Select mode='tags' 
                        // disabled 
                        placeholder="请选择关联服务商" options={connectServiceList} />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="关联服务商信用代码"
                        name={[name, 'craditCode']}
                        rules={[{ required: true, message: '请输入关联服务商信用代码' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Select mode='tags' 
                        // disabled 
                        placeholder="请选择关联服务商信用代码" options={xydmList} />
                        {/* <Input placeholder="请输入关联服务商信用代码" /> */}
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="数字化内容介绍"
                        name={[name, 'digitalContent']}
                        rules={[{ required: true, message: '请输入数字化内容介绍' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <TextArea
                          placeholder="请输入数字化内容介绍"
                          allowClear
                          showCount
                          maxLength={500}
                          style={{
                            minHeight: 120,
                            maxHeight: 200,
                            resize: 'vertical',
                            ...COMMON_FIELD_STYLE,
                          }}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="云应用"
                        name={[name, 'cloundApp']}
                        rules={[{ required: true, message: '请选择云应用' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Select mode="multiple" style={COMMON_FIELD_STYLE}>
                          <Select.Option value="privateCloud">私有云</Select.Option>
                          <Select.Option value="publicCloud">公有云</Select.Option>
                          <Select.Option value="hybridCloud">混合云</Select.Option>
                          <Select.Option value="dedicatedCloud">专有云</Select.Option>
                          <Select.Option value="noCloud">未上云</Select.Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="云应用情况描述"
                        name={[name, 'cloudDesc']}
                        // rules={[{ required: true, message: '请输入云应用情况描述' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <TextArea
                          placeholder="请输入云应用情况描述"
                          allowClear
                          showCount
                          maxLength={500}
                          style={{
                            minHeight: 120,
                            maxHeight: 200,
                            resize: 'vertical',
                            ...COMMON_FIELD_STYLE,
                          }}
                        />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="改造项目开始时间"
                        name={[name, 'programStart']}
                        rules={[{ required: true, message: '请选择改造项目开始时间' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <DatePicker />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="改造项目结束时间"
                        name={[name, 'programEnd']}
                        rules={[{ required: true, message: '请选择改造项目结束时间' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <DatePicker />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="改造项目单项花费 (万元)"
                        name={[name, 'programPay']}
                        rules={[{ required: true, message: '请输入改造项目单项花费 (万元)' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Input placeholder="请输入改造项目单项花费 (万元)" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        label="改造合同"
                        name={[name, 'changeContract']}
                        getValueProps={(values) => {
                          return { values: values }
                        }}
                        rules={[{ required: true, message: '请选择改造合同' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Upload
                          fileList={hetongList[["digitalContentList", name, 'changeContract'].join("_") as any]}
                          beforeUpload={(file) => {
                            handleAutoUpload(file, ["digitalContentList", name, 'changeContract']);
                            return false;
                          }}
                          listType="text"
                          maxCount={1}
                          style={COMMON_FIELD_STYLE}
                        >
                          <Button icon={<UploadOutlined />}>点击上传改造合同</Button>
                        </Upload>
                      </Form.Item>
                      {/* 
                      <Form.Item
                        label="数字化改造需求"
                        {...restField}
                        style={{ marginBottom: 20 }}
                      >
                        <Button
                          style={{ width: '100%' }}
                          onClick={() => setSenceList((prev) => [...prev, prev.length + 1])}
                        >
                          +新增场景
                        </Button>
                      </Form.Item> */}
                      {senceList.map((item, index) => (
                        <div
                          key={item}
                          style={{
                            marginBottom: 24,
                            borderBottom: '1px solid #e8e8e8',
                            paddingBottom: 16,
                          }}
                        >
                          <Row justify="space-between" align="middle">
                            <Col>
                              <div
                                style={{
                                  fontSize: 16,
                                  fontWeight: 500,
                                  color: '#1f2937',
                                  marginBottom: 12,
                                }}
                              >
                                场景 {item}
                              </div>
                            </Col>
                            <Col>
                              <Popconfirm title="是否删除" onConfirm={() => {
                                setSenceList((prev) => prev.filter((_, idx) => idx !== index));
                              }}>
                                <Button
                                  type="link"
                                  danger
                                >
                                  删除
                                </Button>
                              </Popconfirm>

                            </Col>
                          </Row>

                          <Form.Item
                            {...restField}
                            label={`对应的数字化改造需求`}
                            name={[name, item, 'scene']}
                            rules={[{ required: true, message: `请对应的数字化改造需求` }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TreeSelect
                              allowClear
                              placeholder="请对应的数字化改造需求"
                              style={COMMON_FIELD_STYLE}
                              treeData={condition.map((node) => convertNode(node))}
                              treeDefaultExpandAll
                              showSearch
                              onChange={(value) => {
                                if (value) {
                                  const fullPath = fullPathMap[value].join(' / ');
                                  form.setFieldValue(['scenes', name, item, 'scene'], fullPath);
                                }
                              }}
                            />
                          </Form.Item>

                          <Form.Item
                            {...restField}
                            label={`场景描述`}
                            name={[name, item, 'sceneDesc']}
                            rules={[{ required: true, message: `请输入场景描述` }]}
                            style={{ marginBottom: 20 }}
                          >
                            <TextArea
                              placeholder={`${item}请输入场景描述`}
                              allowClear
                              showCount
                              maxLength={500}
                              style={{
                                minHeight: 120,
                                maxHeight: 200,
                                resize: 'vertical',
                                ...COMMON_FIELD_STYLE,
                              }}
                            />
                          </Form.Item>
                        </div>
                      ))}
                    </div>
                  ))}

                  <Form.Item wrapperCol={{ offset: 5, span: 19 }} style={{ marginTop: 40, textAlign: "center" }}>
                    <Button type="primary" onClick={() => add()} >
                      +新增数字化改造内容
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </div>

          <div style={{ marginBottom: 24 }}>
            <div style={{ borderBottom: '1px solid #e8e8e8', marginBottom: 20 }}></div>

            <div
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              预期成效
            </div>

            <Form.Item
              name="innovationDimension"
              label="创新维度"
              rules={[{ required: true, message: '请输入创新维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.研发经费占营业收入比例（%）
2.关键工序数控化率（%）
3.数字化研发设计工具普及率（%）
4.设备联网率（%）
5.新产品产值率（%）
6.设备数字化率（%）
7.协同研发平台覆盖率（%）
8.新产品研制周期（天）`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="marketDimension"
              label="市场维度"
              rules={[{ required: true, message: '请输入市场维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.销售额（万元）
2.主营产品市场占有率（%）
3.线上交易增长率（%）`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="qualityImprovementDimension"
              label="提质维度"
              rules={[{ required: true, message: '请输入提质维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.平均核心产品合格率（%）
2.月度平均产品合格率（%）
3.预测性维护准确率（%）
4.智能检测覆盖率（%）
`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="costReductionDimension"
              label="降本维度"
              rules={[{ required: true, message: '请输入降本维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.生产成本（万元）
2.管理成本（万元）
3.采购成本（万元）
4.研发成本（万元）
5.能耗成本（万元）
`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="efficiencyIncreaseDimension"
              label="增效维度"
              rules={[{ required: true, message: '请输入增效维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.全员劳动生产率（%）
2.销售订单准时交货率（%）
3.采购订单准时交货率（%）
4.生产计划达成率（%）
5.产能利用率（%）
6.库存周转天数（天）
7.库存周转率（%）
8.工单处理时效（h）

`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="greenDimension"
              label="绿色维度"
              rules={[{ required: true, message: '请输入绿色维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`
1.废水排放量（t/d）
2.废气排放量（m³/y）
3.单位产值综合能耗（吨标准煤/万元）
`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="safetyDimension"
              label="安全维度"
              rules={[{ required: true, message: '请输入安全维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder={`1.事故率（%）
2.安全培训合格率（%）
3.安全漏洞修复时效（h）
`}
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="otherDimension"
              label="其他维度"
              rules={[{ required: true, message: '请输入其他维度' }]}
              style={{ marginBottom: 20 }}
            >
              {/* <Input style={COMMON_FIELD_STYLE} /> */}
              <TextArea
                placeholder="请尽量用若干定量指标描述"
                allowClear
                showCount
                maxLength={500}
                style={{
                  minHeight: 120,
                  maxHeight: 200,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>
          </div>
          <Form.Item label={null} style={{ marginTop: 40, textAlign: 'center' }}>
            <Button
              onClick={() => setStepProps((prev) => ({ ...stepProps, current: prev.current - 1 }))}
              type="primary"
              style={{ marginRight: 10 }}
            >
              上一步
            </Button>

            <Button
              type="primary"
              style={{ marginRight: 10 }}
              onClick={submitFun}
            >
              暂存
            </Button>
            {/* <Button
              onClick={() => setStepProps((prev) => ({ ...stepProps, current: prev.current + 1 }))}
              type="primary"
              style={{  marginRight: 10 }}
            >
              下一步
            </Button> */}

            <Button style={{}} type="primary"
              onClick={confirmFun}
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default StepThreePage;
